// koa, koa-router, koa-bodyparser

const koa = require('koa');

const Router = require('koa-router');

const bodyparser = require('koa-bodyparser')

const app = new koa();

const router = new Router();

// 解析post 传来的参数
app.use(bodyparser())

// 创建接口
router.get('/api/test', (ctx) => {
    ctx.body = {
        code: 1,
        msg: '连接成功'
    }
})

// post
router.post('/api/post', (ctx) => {
    // 获取由前端传来的参数
    const { id } = ctx.request.body;

    ctx.body = {
        code: 1,
        msg: `前端传来的id为${id}`
    }
})

// delete === get
router.delete('/api/delete/:id', (ctx) => {
    // 获取前端传来的额参数
    console.log(ctx.params)

    ctx.body = {
        code: 1,
        msg: '请求成功'
    }
})

// put  ==== post
router.put('/api/put', (ctx) => {
    const { name } = ctx.request.body;

    ctx.body = {
        code: 1,
        msg: `前端传来的name为${name}`
    }
})

// all
router.all('/api/all/:id', (ctx) => {
    const { id } = ctx.params;

    const  { name } = ctx.request.body;
    
    console.log(id, name)

    ctx.body = {
        code: 1,
        msg: '请求成功'
    }
})

// 将路由挂载到app中
app.use(router.routes())

// 监听端口号 启动服务
app.listen(3001, () => {
    // 服务器启动成功后 触发的回调函数
    console.log('http://localhost:3001')
})


https://baidu.com?name=张三&age=12&sex=男

